const app = getApp()
const api = app.globalData.api
Page({
    data: {
        num: 0,
        maxNum: 0,
        key: '',
        item: {},
        type: '非条码',
        warehouseOption: [],
        warehousePopup: false,
        positionOption: [],
        positionPopup: false,
        batchOption: [],
        batchPopup: false,
        inventoryNum: 0
    },
    // 获取仓库
    getWarehouse: async function () {
      let that = this
      let res = await api.curlPost('?cla=outStock&fun=getWarehouse', 
      {
        materialId: that.data.item.materialId,
        unit: that.data.item.unit
      })
      if (res.code === 1) {
          that.setData({
            warehouseOption: res.data
          })
      }
    },
    // 获取库位
    getPosition: async function (warehouseId, positionId) {
      if(warehouseId){
        let that = this
        let res = await api.curlPost('?cla=outStock&fun=getPosition', 
        {
          materialId: that.data.item.materialId, 
          unit: that.data.item.unit,
          warehouseId: warehouseId, 
          positionId: positionId
        })
        if (res.code === 1) {
          that.setData({
            positionOption: res.data.positionOption,
            ['item.position']: res.data.position,
            ['item.positionId']: res.data.positionId,
          })
        }
      }
    },
    // 获取批次
    getBatch: async function (warehouseId, positionId, batch) {
      if(warehouseId && positionId){
        let that = this
        let res = await api.curlPost('?cla=outStock&fun=getBatch', 
        {
          materialId: that.data.item.materialId,
          unit: that.data.item.unit,
          warehouseId: warehouseId,
          positionId: positionId, 
          batch: batch
        })
        if (res.code === 1) {
          that.setData({
            batchOption: res.data.batchOption,
            // ['item.position']: res.data.position,
            // ['item.positionId']: res.data.positionId,
            ['item.batchText']: res.data.batchText,
            ['item.batch']: res.data.batch,
          })
        }
      }
    },
    getInventory: async function (warehouseId, positionId, batch) {
      if(warehouseId && positionId){
        let that = this
        let res = await api.curlPost('?cla=outStock&fun=getInventory', 
        {
          materialId: that.data.item.materialId,
          unit: that.data.item.unit,
          warehouseId: warehouseId,
          positionId: positionId, 
          batch: batch
        })
        if (res.code === 1) {
          that.setData({
            inventoryNum: res.data.inventoryNum,
          })
        }
      }
    },
    main: async function () {
      await this.getWarehouse()
      await this.getPosition(this.data.item.warehouseId, this.data.item.positionId)
      await this.getBatch(this.data.item.warehouseId, this.data.item.positionId, this.data.item.batch)
  },
    putOut: async function (e) {
        let data = e.detail.value
        if (data) {
          if(parseFloat(this.data.num) <= 0){
            api.showToast('出库数量必须大于0')
            return
          }
          if(data['outAllowZero'] != '1' && parseFloat(this.data.num) > this.data.inventoryNum){
            api.showToast('出库数量不能大于库存数量'+this.data.inventoryNum)
            return
          }
          // 初始化部分值
          data['outNum'] = this.data.num
          data['type'] = '本次出库'
          data['key'] = this.data.key
          data['time'] = api.formatDate(new Date().getTime(), 'datetime')
          let mergedObj = { ...this.data.item, ...data };  
          api.showToast('确认成功')
          wx.setStorageSync('outData', mergedObj)
          wx.navigateBack({
              delta: 1
          })
        }
    },
    onStepperChange(e) {  
      this.setData({  
        num: e.detail,
      });  
    },  
    inputValue(e) {  
      let obj = e.currentTarget.dataset
      let field = 'item.'+obj.field
      this.setData({  
        [field]: e.detail,
      });  
    },
    // 关闭
    onClose: function (e) {
      let obj = e.currentTarget.dataset
      if (obj) {
          this.setData({[obj.target]: false})
      }
    },
    funRouting(type, detail) {
      switch (type) {
          case 'warehouseId':
              let warehouse = detail.value
              this.setData({
                  ['item.warehouse']: warehouse['text']
              })
              return warehouse['value']
          case 'positionId':
              let position = detail.value
              this.setData({
                  ['item.position']: position['text']
              })
              return position['value']
          case 'batch':
                let batch = detail.value
                this.setData({
                    ['item.batchText']: batch['text']
                })
                return batch['value']
      }
    },
    // 确认选择
    onConfirm: async function (e) {
        let obj = e.currentTarget.dataset
        let prefix = obj.prefix ? obj.prefix : 'item'
        let field = (prefix ? prefix + '.' : '') + obj.field
        let val = this.funRouting(obj.field, e.detail)
        this.setData({
            [obj.target]: false,
            [field]: val,
        })
        // 获取库位
        if(obj.field === 'warehouseId'){
          await this.getPosition(val, this.data.item.positionId)
        }else if(obj.field === 'positionId'){
          console.log(this.data.item)
          await this.getBatch(this.data.item.warehouseId, val, this.data.item.batch)
        }else if(obj.field === 'batch'){
          await this.getInventory(this.data.item.warehouseId, this.data.item.positionId, val)
        }
    },
    showPopup: function (obj) {
      let popup = obj.currentTarget.dataset.show
      if (popup) {
          this.setData({
              [popup]: true
          });
      }
    },
    onLoad: async function (options) {
      wx.removeStorageSync('outData')
      let string = options.data ? options.data : '',
          key = options.key ? options.key : ''
      wx.setNavigationBarTitle({
          title: '按物料出库'
      })
      if (string.length < 1) {
          api.showToast('参数错误')
      } else {
          const data = api.jsonToArray(api.urlDecode(string))
          let outNum = data.outNum ? data.outNum : 0
          this.setData({
            key: key,
            num: outNum > 0 ? outNum : data.orderNum - data.num,
            maxNum: data.inStockLimit != '1' ? (data.orderNum - data.num + outNum) : Number.MAX_SAFE_INTEGER,
            item: data
          })
      }
      await this.main()
    }
});